#region

using Serilog;
using Serilog.Events;

#endregion

namespace AbpWebHostTest;

public class Program
{
    public static async Task<int> Main(string[] args)
    {
        var configFile = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json";
        var buildConfiguration = GetBuildConfiguration(configFile);
        var configuration = buildConfiguration.Build();
        Log.Logger = new LoggerConfiguration()
#if DEBUG
            .MinimumLevel.Debug()
#else
            .MinimumLevel.Information()
#endif
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
            .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .ReadFrom.Configuration(configuration)
            .WriteTo.Async(c => c.Console())
            .CreateLogger();

        try
        {
            Log.Information("Starting Host.");
            var builder = WebApplication.CreateBuilder(args);

            builder.Host.ConfigureAppConfiguration((hostContext, configurationBuilder) =>
            {
                var env = hostContext.HostingEnvironment;
                if (args != null)
                {
                    configurationBuilder.AddCommandLine(args);
                }
            });
            builder.Host.AddAppSettingsSecretsJson()
                .UseAutofac()
                .UseSerilog();

            await builder.AddApplicationAsync<HttpApiHostModule>();
            var app = builder.Build();
            ConfigurationManager c = builder.Configuration;
            var appConfig = c.GetSection("App");
            var corsOrigins = appConfig["CorsOrigins"];
            Console.WriteLine($"corsOrigins = {corsOrigins}");
            await app.InitializeApplicationAsync();
            await app.RunAsync();
            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly!");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    private static IConfigurationBuilder GetBuildConfiguration(string configFile)
    {
        Console.WriteLine($"ConfigFile:{configFile}");
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", false, true)
            .AddJsonFile(configFile, true, true);

        return configuration;
    }
}